<?php

namespace app\api\controller\login;

use app\common\controller\BasicApi;
use app\common\model\GoodsConfigModel;
use app\common\model\GoodsLogModel;
use app\common\model\GoodsModel;
use app\common\model\GoodsProductModel;
use app\common\model\OrderConfigModel;
use app\common\model\OrderLogModel;
use app\common\model\OrderModel;
use app\common\model\OrderGoodsModel;
use app\api\controller\Member;
use app\common\model\OrderPaylogModel;
use app\common\model\PosthouseModel;
use app\common\model\UserModel;
use think\db;

class Order extends Member
{
    /**
     * 渲染订单
     */
    public function renderOrder()
    {
        $goods_str = $this->request->get('goods_str');
        $goods_str = json_decode($goods_str,true);
        $goods_id = $goods_str['id'];
        $spec = $goods_str['spec'];
        $num = $goods_str['num'];
        $price = $goods_str['price'];
        $goods = GoodsModel::where('status', 1)
            ->where('id', $goods_id)
            ->field('id,name,title,logo')
            ->find();
        if(!empty($spec)){
            $goods['spec'] = array_filter(explode(';',$spec));
        }else{
            $goods['spec'] = '';
        }
        $goods['num'] = $num;
        $goods['price'] = $price;
        $result['goods'] = $goods;
        $result['total_price'] = number_format($price*$num,2);
        $result['amount_price'] = number_format($price*$num,2);
        if (!empty($result)) {
            $this->success('渲染订单成功！', $result, 200);
        } else {
            $this->error('渲染订单失败！', '', 400);
        }
    }

    /**
     * 提交订单
     */
    public function createOrder(){
        $user = $this->getMember();
        $post_id = $this->request->post('post_id');
        $mycoupon_id = $this->request->post('mycoupon_id');
        $coupon_total = $this->request->post('coupon_total');
        if(empty($post_id)) $this->error('请选择驿站！','',400);
        $goods_str = $this->request->post('goods_str');
        $goods_str = json_decode($goods_str,true);
        $goods_id = $goods_str['id'];
        $spec = $goods_str['spec'];
        $num = $goods_str['num'];
        $price = $goods_str['price'];

        $order_total = number_format($price*$num,2);
        $order_amount = number_format($order_total-number_format($coupon_total,2),2);

        $create_time = date('Y-m-d H:i:s',time());
        $order_no = date('Ymd',time()).rand(1000,9999);

        //自提时间
        //1、常规的
        $goods_ziti = intval(GoodsConfigModel::where(['key'=> 'goods_ziti'])->value('goods_id'));
        $ziti_time =date('Y-m-d H:i:s',strtotime("+$goods_ziti day",time()));
        //2、查看是否是接龙商品
        $jielong_goods_id = intval(GoodsConfigModel::where(['key'=> 'jielong'])->value('goods_id'));
        if($goods_id==$jielong_goods_id){
            $jielong_ziti = GoodsConfigModel::where(['key'=> 'jielong_ziti'])->value('goods_id');
            $ziti_time =  date("Y-m-d H:i:s",strtotime("+$jielong_ziti day",time()));
        }
        //3、查看是否是预售商品
        $monday_id = GoodsConfigModel::where('key','monday')->value('goods_id');
        if($goods_id==$monday_id){
            $ziti_time =  date('Y-m-d H:i:s',strtotime("next monday"));
        }
        $tuesday_id = GoodsConfigModel::where('key','tuesday')->value('goods_id');
        if($goods_id==$tuesday_id){
            $ziti_time =  date('Y-m-d H:i:s',strtotime("next tuesday"));
        }
        $wednesday_id = GoodsConfigModel::where('key','wednesday')->value('goods_id');
        if($goods_id==$wednesday_id){
            $ziti_time =  date('Y-m-d H:i:s',strtotime("next wednesday"));
        }
        $thursday_id = GoodsConfigModel::where('key','thursday')->value('goods_id');
        if($goods_id==$thursday_id){
            $ziti_time =  date('Y-m-d H:i:s',strtotime("next thursday"));
        }
        $friday_id = GoodsConfigModel::where('key','friday')->value('goods_id');
        if($goods_id==$friday_id){
            $ziti_time =  date('Y-m-d H:i:s',strtotime("next friday"));
        }
        $saturday_id = GoodsConfigModel::where('key','saturday')->value('goods_id');
        if($goods_id==$saturday_id){
            $ziti_time =  date('Y-m-d H:i:s',strtotime("next saturday"));
        }
        $sunday_id = GoodsConfigModel::where('key','sunday')->value('goods_id');
        if($goods_id==$sunday_id){
            $ziti_time =  date('Y-m-d H:i:s',strtotime("next sunday"));
        }

        $result = OrderModel::create([
            'order_no'=>$order_no,
            'post_id'=>$post_id,
            'status'=>ORDER_STATUS_PAY,
            'user_id'=>$user['id'],
            'coupon_id'=>$mycoupon_id,
            'order_total'=>$order_total?$order_total:0,
            'coupon_total'=>$coupon_total?$coupon_total:0,
            'order_amount'=>$order_amount?$order_amount:0,
            'create_time'=>$create_time,
            'ziti_time'=>$ziti_time
        ]);
        $order_id = $result['id'];
        $goods =GoodsModel::where('status', 1)
            ->where('id', $goods_id)
            ->field('*')
            ->find();
        OrderGoodsModel::create([
            'order_id'=>$order_id,
            'goods_id'=>$goods_id,
            'goods_spec'=>$spec,
            'goods_num'=>$num,
            'goods_price'=>$price,
            'coupon_total'=>$coupon_total,
            'goods_name'=>$goods['name'],
            'goods_logo'=>$goods['logo'],
        ]);
        //创建订单就减少库存
        if($goods['type']==1) {
            //单规格
            GoodsModel::where('id',$goods_id)->setDec('stock',$num);
           }else {
            //多规格
            GoodsProductModel::where(['goods_id'=>$goods_id,'spec'=>$spec])->setDec('stock',$num);
        }

        //订单日志-用户
        OrderLogModel::where('')->insert([
            'order_id'=>$order_id,
            'operate_id'=>$user['id'],
            'operate_name'=>$user['nickname'],
            'content'=> '创建订单',
            'type'=> 1,
            'create_time'=>date('Y-m-d H:i:s',time())
        ]);

        \think\facade\Hook::listen('sys_msg', [
            'title' => '有新订单生成',
            'desc'  => '有新订单生成,请查看！'
        ]);
        if(!empty($order_id)){
            $this->success('提交订单成功！',$order_id,200);
        }else{
            $this->error('提交订单失败！','',400);
        }
    }


    /**
     * 统一支付接口
     */
    public function wechatPay()
    {
        $order_id = $this->request->post('order_id');
        if(empty($order_id)) $this->error('订单id为空！','',400);
        $user_id = $this->getMember()['id'];
        $order_info = OrderModel::where('id',$order_id)->field('id,order_amount')->find();
        $order_param = $this->orderParams($order_info,$user_id);
        $config = config('wechat.miniapp');
        $payment = new \WeChat\Pay($config);
        $result = $payment->createOrder($order_param);
        $options = $payment->createParamsForJsApi($result['prepay_id']);
        $this->success('调用支付成功', $options,200);
    }

    /**
     * 处理订单参数
     */
    protected function orderParams(&$order_info,$user_id)
    {
        if (empty($order_info)) {
            $this->error('没有对应的订单信息','', 400);
        }
        if(!empty($order_info['pay_time'])){
            $this->error('该订单已支付过了','', 400);
        }
        $openid = UserModel::where(['id'=>$user_id])->value('openid');
        if (!$openid){
            $this->error('用户不存在','', 400);
        }

        /*支付参数body*/
        $data['body'] = "订单id{$order_info['id']}";
        $data['openid'] = $openid;
        $data['out_trade_no'] = date('YmdHis') . rand(1000000,9999999);//生成支付交易号并更新订单表
        OrderModel::where('id',$order_info['id'])->update(['trade_no'=>$data['out_trade_no']]);

        if(config('app.pay_debug')){
            $data['total_fee'] = 1;//测试1分钱
        }else{
            $data['total_fee'] = $order_info['order_amount']*100;
        }

        $data['trade_type'] = 'JSAPI';
        $data['notify_url']     = request()->domain().'/'.'api/notify/wxpay';
        return $data;
    }

    /**
     * 我的-订单
     */
    public function getOrderList(){
        $status = $this->request->get('status');
        $where = [];
        switch ($status){
            case 1: $where = ['status'=>ORDER_STATUS_PAY];break;
            case 2: $where = ['status'=>ORDER_STATUS_ZITI];break;
            case 3: $where = ['status'=>ORDER_STATUS_FINISH];break;
        }
        $user_id = $this->getMember()['id'];
        $page = $this->request->get('page', 1);
        $order = OrderModel::where('user_id',$user_id)->where($where)->page($page,10)->order('id desc')->select();
        foreach ($order as &$value){
            $goods = OrderGoodsModel::where('order_id',$value['id'])->find();
            $value['goods'] = $goods;
            switch ($value['status']){
                case ORDER_STATUS_CANCEL: $value['status_desc'] = '已取消';break;
                case ORDER_STATUS_PAY: $value['status_desc'] = '待付款';break;
                case ORDER_STATUS_ZITI: $value['status_desc'] = '待自提';break;
                case ORDER_STATUS_FINISH: $value['status_desc'] = '已完成';break;
                default : $value['status_desc'] = '已取消';break;
            }
            $value['ziti_time'] = date('Y-m-d',strtotime($value['ziti_time']));
        }

        if (!empty($order)) {
            $this->success('获取订单列表成功！', $order, 200);
        } else {
            $this->error('获取订单列表失败！', '', 400);
        }
    }

    /**
     * 订单详情页
     */
    public function getOrderDetail()
    {
        $order_id = $this->request->get('order_id');
        if(empty($order_id)) $this->error('订单id为空！','',400);
        $order = OrderModel::where('id',$order_id)
            ->field('*')
            ->find();
        $goods = OrderGoodsModel::where('order_id',$order_id)->find();
        $result['goods'] = $goods;
        $result['order'] = $order;
        $result['post'] = PosthouseModel::where('id',$order['post_id'])->find();

        if (!empty($result)) {
            $this->success('渲染订单详情页成功！', $result, 200);
        } else {
            $this->error('渲染订单详情页失败！', '', 400);
        }
    }

    /**
     * 确认收货
     */
    public function takeGoods(){
        $order_id = $this->request->post('order_id');
        if(empty($order_id)) $this->error('订单id为空！','',400);
        $order = OrderModel::where(['id'=>$order_id])->update(['status'=>ORDER_STATUS_FINISH]);
        /**
         * 计算提成给驿站长/合伙人
         * 调用微信商户平台转账给个人接口
         */
        //找到订单金额和用户openid
        $order_info =  OrderModel::where(['id'=>$order_id])->field('post_id,order_amount,user_id')->find();

        //找到商品（只有一种）
        $order_goods_info =  OrderGoodsModel::where(['order_id'=>$order_id])->field('goods_id')->find();

        //找到对应的驿站长和合伙人分成比例
        $goods_info =  GoodsModel::where(['id'=> $order_goods_info['goods_id']])->field('poster_rate,partner_rate,name')->find();
        $poster_rate = $goods_info['poster_rate'];
        $partner_rate = $goods_info['partner_rate'];

        //找到订单对应的驿站的驿站长和合伙人
        $posthouse = PosthouseModel::where('id',$order_info['post_id'])->field('poster_userid,partner_userid')->find();
        $poster_userid = $posthouse['poster_userid'];
        $poster_user = UserModel::where('id',$poster_userid)->find();
        $partner_userid = $posthouse['partner_userid'];
        $partner_user = UserModel::where('id',$partner_userid)->find();

        $order_amount = $order_info['order_amount'];
        $poster_order_amount = $order_amount * $poster_rate/100;
        $partner_order_amount = $order_amount * $partner_rate/100;

        //写入驿站长与合伙人分润表
        //驿站长
        OrderPaylogModel::where('')->insert([
            'openid'=>$poster_user['openid'],
            'poster_id'=>$poster_userid,
            'order_id'=>$order_id,
            'need_pay'=>$poster_order_amount,
            'has_pay'=>0,
            'not_pay'=>$poster_order_amount,
            'create_time'=>date('Y-m-d H:i:s',time()),
            'type'=>1
        ]);
        //合伙人
        OrderPaylogModel::where('')->insert([
            'openid'=>$partner_user['openid'],
            'partner_id'=>$partner_userid,
            'order_id'=>$order_id,
            'need_pay'=>$partner_order_amount,
            'has_pay'=>0,
            'not_pay'=>$partner_order_amount,
            'create_time'=>date('Y-m-d H:i:s',time()),
            'type'=>2
        ]);
        //写入商品日志表
        GoodsLogModel::where('')->insert([
            'user_id'=>$order_info['user_id'],
            'content'=> '你的商品'.$goods_info['name'].'已经成功自提',
            'remark'=> '',
            'create_time'=>date('Y-m-d H:i:s',time())
        ]);
        if (!empty($order)) {
            //订单日志-用户
            $nickname = UserModel::where('id',$order_info['user_id'])->value('nickname');
            OrderLogModel::where('')->insert([
                'order_id'=>$order_id,
                'operate_id'=>$order_info['user_id'],
                'operate_name'=>$nickname,
                'content'=> '用户确认自提',
                'type'=> 1,
                'create_time'=>date('Y-m-d H:i:s',time())
            ]);

            $this->success('用户确认自提成功！', $order, 200);
        } else {
            $this->error('用户确认自提失败！', '', 400);
        }

    }


    /**
     * 获取倒计时秒数
     */
    public function getRemainTime(){
        $order_id = $this->request->get('order_id');
        if(!empty($order_id)){
            //获得创建订单的时间
            $create_time = OrderModel::where('id',$order_id)->value('create_time');
            $remain_time = OrderConfigModel::where('key','pay_time')->value('value');
            $remain_time = strtotime($create_time) - time() + $remain_time * 60 >= 0? (strtotime($create_time) - time() + $remain_time * 60) * 1000:0;
        }else{
            $remain_time = OrderConfigModel::where('key','pay_time')->value('value');
            $remain_time = $remain_time * 60 * 1000;
        }
        if (!empty($remain_time)||$remain_time==0) {
            $this->success('获取倒计时秒数成功！', $remain_time, 200);
        } else {
            $this->error('获取倒计时秒数失败！', '', 400);
        }
    }


    /**
     * 取消订单
     */
    public function cancelOrder(){
        $order_id = $this->request->post('order_id');
        if(empty($order_id)) $this->error('订单id为空！','',400);
        $order = OrderModel::where(['id'=>$order_id])->update(['status'=>ORDER_STATUS_CANCEL]);
        //库存恢复
        $goods_id = OrderGoodsModel::where('order_id',$order_id)->field('goods_id')->find()['goods_id'];
        GoodsModel::where('id',$goods_id)->setInc('stock');
        if (!empty($order)) {
            $this->success('取消订单成功！', $order, 200);
        } else {
            $this->error('取消订单失败！', '', 400);
        }
    }

    /**
     * 微信商户转账给个人测试
     */
    public function send_money_test(){
        $config = config('wechat.miniapp');
        $payment = new \WeChat\Pay($config);
        $openid = 'o-M7q4stWzGe-oEc4qEOcS-v7kFo';//熊猫店长丶
        $options = [
            'partner_trade_no' => time().uniqid('hdd'),
            'openid'           => $openid,
            'check_name'       => 'NO_CHECK',
            'amount'           => 0.3 * 100,
            'desc'             => '转账给艺术家用户',
            'spbill_create_ip' => '127.0.0.1',
        ];
        $result = $payment->createTransfers($options);
        dump($result);die;
    }
}
